package com.datawale.vh.demo.work.controller;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Component
@EnableScheduling
public class WebRTCWebSocketHandler extends AbstractWebSocketHandler {
    private final AtomicReference<WebSocketSession> sessionRef = new AtomicReference<>();
    private final Path videoPath = Paths.get("/data/video/video.mp4"); // 视频文件目录路径
    private LocalDateTime lastCheckTime = LocalDateTime.now();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if (sessionRef.get() != null) {
            // 如果用户已经有连接，则关闭新的连接
            session.close();
            return;
        }

        sessionRef.set(session);

        try {
            // 推送初始视频流
            byte[] videoData = Files.readAllBytes(videoPath);
            String base64Video = Base64.getEncoder().encodeToString(videoData);

            session.sendMessage(new TextMessage(base64Video));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理从客户端接收到的文本消息
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理WebSocket传输错误
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        if (sessionRef.compareAndSet(session, null)) {
            // 用户连接关闭后的处理
        }
    }

    @Scheduled(fixedDelay = 10000) // 每10秒执行一次
    private void checkNewVideos() {
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(lastCheckTime, now);
        if (duration.getSeconds() < 10) {
            return;
        }

        try {
            List<Path> newVideos = findNewVideos();
            for (Path newVideo : newVideos) {
                byte[] videoData = Files.readAllBytes(newVideo);
                sendMessageToClient(videoData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        lastCheckTime = now;
    }

    private List<Path> findNewVideos() throws IOException {
        List<Path> newVideos = new ArrayList<>();

        Files.walkFileTree(videoPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (attrs.isRegularFile() && isVideoFile(file) && isNewVideoFile(file)) {
                    newVideos.add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });

        return newVideos;
    }
    private boolean isVideoFile(Path file) {
        String fileName = file.getFileName().toString();
        return fileName.toLowerCase().endsWith(".mp4") || fileName.toLowerCase().endsWith(".mkv");
    }

    private boolean isNewVideoFile(Path file) throws IOException {
        BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
        FileTime creationTime = attrs.creationTime();
        LocalDateTime creationDateTime = LocalDateTime.ofInstant(creationTime.toInstant(), ZoneId.systemDefault());
        return creationDateTime.isAfter(lastCheckTime);
    }

    private void sendMessageToClient(byte[] videoData) {
        WebSocketSession session = sessionRef.get();
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(videoData));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
